﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace Me.Prettyprint.Cassandra.Utils
{
    public class List
    {
        public static List<List<K>> Partition<K>(List<K> keys, int partitions)
        {
            if (keys != null && keys.Count > 0)
            {
                return new Partition<K>(keys, partitions);
            }
            else
            {
                throw new SystemException("Key list cannot be NULL or empty");
            }
        }
    }
    public class Partition<K> : List<List<K>>
    {
        private List<K> originalList;
        private int partitions;

        public Partition()
        {
        }
        public Partition(List<K> list, int count)
        {
            originalList = list;
            partitions = count;
        }
        public List<K> Get(int index)
        {
            CheckElementIndex(index);
            int start = index * partitions;
            int end = Math.Min(start + partitions, originalList.Count);
            List<K> sublist = new List<K>();
            for (int i = start; i < end; i++)
            {
                sublist.Add(originalList[i]);
            }
            return sublist;
        }
        public int NumberOfPartitions
        {
            get
            {
                return this.partitions;
            }
        }
        public List<K> OriginalList
        {
            get
            {
                return this.originalList;
            }
        }
        protected void CheckElementIndex(int index)
        {
            if (index < 0 || index >= originalList.Count)
            {
                throw new IndexOutOfRangeException(String.Format("{0} is the size, {1} is out of range.", originalList.Count, index));
            }
        }
    }
}
